package com.example.demo.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
import java.util.Objects;

@Slf4j
public class WordReadUtil {

    /**只获取word文本内容 XWPFWordExtractor*/
    public static String readWordOnlyContent(String path){
        String result = "";
        File file = new File(path);
        String text;
        try {
            FileInputStream fs = new FileInputStream(file);
            XWPFDocument doc = new XWPFDocument(fs);
            XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
            text = extractor.getText();
            extractor.close();
            fs.close();
            result = text;
        } catch (IOException e) {
            log.error("读取word文本错误：" + e.getMessage() + "\r\n堆栈信息：" + e.getStackTrace());
        }
        return result;
    }

    /**获取word文本内容及属性等精确信息*/
    public static String readWord(String path){
        XWPFDocument xwpfDocument = null;
        String htmlText = "";
        try {
            xwpfDocument = new XWPFDocument(new FileInputStream(path));
            /**获取word中的所有段落与表格*/
            List<IBodyElement> elements = xwpfDocument.getBodyElements();
            for (IBodyElement element : elements) {
                /**段落*/
                if(element instanceof XWPFParagraph){
                    htmlText += getParagraphText((XWPFParagraph) element);
                }
                /**表格*/
                else if(element instanceof XWPFTable){
                    htmlText += getTableText((XWPFTable) element);
                }
            }
            xwpfDocument.close();
        } catch (Exception e) {
            log.error("读取word完整信息错误：" + e.getMessage() + "\r\n堆栈信息：" + e.getStackTrace());
        }
        return htmlText;
    }

    /**获取段落内容*/
    private static String getParagraphText(XWPFParagraph paragraph){
        /**获取段落中所有内容*/
        List<XWPFRun> runs = paragraph.getRuns();
        if(runs.size() == 0){
            return "";
        }
        StringBuffer runText = new StringBuffer();
        for (XWPFRun run : runs) {
            runText.append(run.text());
        }
        /**对齐方式*/
        runText.append("，对齐方式：").append(paragraph.getAlignment().name()).append("\n");
        return runText.toString();
    }

    /**获取表格内容*/
    private static String getTableText(XWPFTable table){
        String result = "";
        /**获取表格数据行*/
        List<XWPFTableRow> rows = table.getRows();
        if(rows.size() > 0){
            for (int i = 0; i < rows.size(); i++) {
                XWPFTableRow row = rows.get(i);
                /**获取每行的数据列*/
                List<XWPFTableCell> cells = row.getTableCells();
                for (XWPFTableCell cell : cells) {
                    String cellText = "";
                    /**简单获取内容(只有内容无对齐方式)*/
//                    String text = cell.getText();
                    /**获取完整单元格(单元格内可以加段落与表格)*/
                    List<XWPFParagraph> paragraphs = cell.getParagraphs();
                    for (XWPFParagraph paragraph : paragraphs) {
                        cellText += getParagraphText(paragraph);
                    }
                    /**获取单元格跨列个数*/
                    BigInteger cellGridSpanNum = getCellGridSpanNum(cell);
                    if(Objects.nonNull(cellGridSpanNum)){
                        cellText += cellGridSpanNum;
                    }
                    result += cellText;
                }
            }
        }
        return result;
    }

    /**获取word表格单元格跨列个数*/
    public static BigInteger getCellGridSpanNum(XWPFTableCell cell){
        BigInteger num = null;
        /**获取单元格跨列*/
        CTDecimalNumber gridSpan = cell.getCTTc().getTcPr().getGridSpan();
        if(Objects.nonNull(gridSpan)){
            num = gridSpan.getVal();
        }
        return num;
    }

    /**获取word中所有图片,下载到word文件所在文件夹*/
    public static void getWordPictures(String path){
        try {
            XWPFDocument document = new XWPFDocument(new FileInputStream(path));
            List<XWPFPictureData> picLists = document.getAllPictures();
            for (XWPFPictureData pic : picLists) {
                /**图片名称*/
                System.out.println("图片名称：\t" + pic.getFileName());
                /**图片类型*/
                System.out.println("图片类型：\t" + pic.getPictureType());
                /**写入doc所在文件夹*/
                File file = new File(path);
                byte[] data = pic.getData();
                String imagePath = file.getParent() + File.separator + pic.getFileName();
                FileOutputStream fos = new FileOutputStream(imagePath);
                fos.write(data);
            }
        } catch (IOException e) {
            log.error("保存word图片错误：" + e.getMessage() + "\r\n堆栈信息：" + e.getStackTrace());
        }
    }
}
